{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.6.10"
    },
    "colab": {
      "name": "14_Modeling_Protein_Ligand_Interactions_With_Atomic_Convolutions.ipynb",
      "provenance": []
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f7FPLsj4nB-6",
        "colab_type": "text"
      },
      "source": [
        "# Tutorial Part 14: Modeling Protein-Ligand Interactions with Atomic Convolutions\n",
        "\n",
        "This deepchem tutorial introduces Atomic Convolutional Model. We'll see the structure of the Atomic Conv Model and write a simple program to run Atomic Convolutions.\n",
        "\n",
        "### Structure\n",
        "ACNN’s directly exploit the local three-dimensional structure of molecules to hierarchically learn more complex chemical features by optimizing both the model and featurization simultaneously in an end-to-end fashion.\n",
        "\n",
        "The atom type convolution makes use of a neighbor-listed distance matrix to extract features encoding local chemical environments from an input representation (Cartesian atomic coordinates) that does not necessarily contain spatial locality. Following are the methods use to build ACNN architecture:\n",
        "\n",
        "- #### Distance Matrix\n",
        "The distance matrix R is constructed from the Cartesian atomic coordinates X. It calculates distance from the distance tensor D. The distance matrix construction accepts as input a (N, 3) coordinate matrix C. This matrix is “neighbor listed” into a (N, M) matrix R.\n",
        "\n",
        "```python\n",
        "    R = tf.reduce_sum(tf.multiply(D, D), 3)     # D: Distance Tensor\n",
        "    R = tf.sqrt(R)                              # R: Distance Matrix\n",
        "    return R\n",
        "```\n",
        "\n",
        "- #### Atom type convolution\n",
        "The output of the atom type convolution is constructed from the distance matrix R and atomic number matrix Z. The matrix R is fed into a (1x1) filter with stride 1 and depth of Na , where Na is the number of unique atomic numbers (atom types) present in the molecular system. The atom type convolution kernel is a step function that operates on neighbor distance matrix R.\n",
        "\n",
        "- #### Radial Pooling layer\n",
        "Radial Pooling is basically a dimensionality reduction process which down-samples the output of the atom type convolutions. The reduction process prevents overfitting by providing an abstracted form of representation through feature binning, as well as reducing the number of parameters learned.\n",
        "Mathematically, radial pooling layers pool over tensor slices (receptive fields) of size (1xMx1) with stride 1 and a depth of Nr, where Nr is the number of desired radial filters.\n",
        "\n",
        "- #### Atomistic fully connected network\n",
        "Atomic Conolution layers are stacked by feeding the flattened(N, Na x Nr) output of radial pooling layer into the atom type convolution operation. Finally, we feed the tensor row-wise (per-atom) into a fully-connected network. The\n",
        "same fully connected weights and biases are used for each atom in a given molecule.\n",
        "\n",
        "Now that we have seen the structural overview of ACNNs, we'll try to get deeper into the model and see how we can train it and what do we expect as the output.\n",
        "\n",
        "For the training purpose, we will use the publicly available PDBbind dataset. In this example, every row reflects a protein-ligand complex, and the following columns are present: a unique complex identifier; the SMILES string of the ligand; the binding affinity (Ki) of the ligand to the protein in the complex; a Python list of all lines in a PDB file for the protein alone; and a Python list of all lines in a ligand file for the ligand alone.\n",
        "\n",
        "## Colab\n",
        "\n",
        "This tutorial and the rest in this sequence are designed to be done in Google colab. If you'd like to open this notebook in colab, you can use the following link.\n",
        "\n",
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepchem/deepchem/blob/master/examples/tutorials/14_Modeling_Protein_Ligand_Interactions_With_Atomic_Convolutions.ipynb)\n",
        "\n",
        "## Setup\n",
        "\n",
        "To run DeepChem within Colab, you'll need to run the following cell of installation commands. This will take about 5 minutes to run to completion and install your environment."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2xCQyOInB_D",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 323
        },
        "outputId": "6923424c-4066-497a-eae5-57a08ff43960"
      },
      "source": [
        "!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py\n",
        "import conda_installer\n",
        "conda_installer.install()\n",
        "!/root/miniconda/bin/conda info -e"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n",
            "                                 Dload  Upload   Total   Spent    Left  Speed\n",
            "\r  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\r100  3489  100  3489    0     0  27046      0 --:--:-- --:--:-- --:--:-- 27046\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "stream",
          "text": [
            "add /root/miniconda/lib/python3.6/site-packages to PYTHONPATH\n",
            "python version: 3.6.9\n",
            "fetching installer from https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh\n",
            "done\n",
            "installing miniconda to /root/miniconda\n",
            "done\n",
            "installing rdkit, openmm, pdbfixer\n",
            "added omnia to channels\n",
            "added conda-forge to channels\n",
            "done\n",
            "conda packages installation finished!\n"
          ],
          "name": "stderr"
        },
        {
          "output_type": "stream",
          "text": [
            "# conda environments:\n",
            "#\n",
            "base                  *  /root/miniconda\n",
            "\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jFQmra_fFE8U",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 361
        },
        "outputId": "77fd2bd3-f934-433f-a090-868611976583"
      },
      "source": [
        "!pip install --pre deepchem\n",
        "import deepchem\n",
        "deepchem.__version__"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Collecting deepchem\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/b5/d7/3ba15ec6f676ef4d93855d01e40cba75e231339e7d9ea403a2f53cabbab0/deepchem-2.4.0rc1.dev20200805054153.tar.gz (351kB)\n",
            "\u001b[K     |████████████████████████████████| 358kB 2.8MB/s \n",
            "\u001b[?25hRequirement already satisfied: joblib in /usr/local/lib/python3.6/dist-packages (from deepchem) (0.16.0)\n",
            "Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from deepchem) (1.18.5)\n",
            "Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from deepchem) (1.0.5)\n",
            "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from deepchem) (0.22.2.post1)\n",
            "Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from deepchem) (1.4.1)\n",
            "Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->deepchem) (2.8.1)\n",
            "Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->deepchem) (2018.9)\n",
            "Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas->deepchem) (1.15.0)\n",
            "Building wheels for collected packages: deepchem\n",
            "  Building wheel for deepchem (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for deepchem: filename=deepchem-2.4.0rc1.dev20200805144642-cp36-none-any.whl size=438624 sha256=7e5b9b5d387726c10af3665c3fabc3cf8955c98122717ba2e3ccdb016174e99e\n",
            "  Stored in directory: /root/.cache/pip/wheels/41/0f/fe/5f2659dc8e26624863654100f689d8f36cae7c872d2b310394\n",
            "Successfully built deepchem\n",
            "Installing collected packages: deepchem\n",
            "Successfully installed deepchem-2.4.0rc1.dev20200805144642\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            },
            "text/plain": [
              "'2.4.0-rc1.dev'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "W1cCOOYXnB_L",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import deepchem as dc\n",
        "import os\n",
        "from deepchem.utils import download_url"
      ],
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "S_N207VWnB_R",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "download_url(\"https://s3-us-west-1.amazonaws.com/deepchem.io/datasets/pdbbind_core_df.csv.gz\")\n",
        "data_dir = os.path.join(dc.utils.get_data_dir())\n",
        "dataset_file= os.path.join(dc.utils.get_data_dir(), \"pdbbind_core_df.csv.gz\")\n",
        "raw_dataset = dc.utils.save.load_from_disk(dataset_file)"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "snei1ST1nB_a",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 170
        },
        "outputId": "e64c16d0-8b1a-47a6-8e92-b6895341d4ab"
      },
      "source": [
        "print(\"Type of dataset is: %s\" % str(type(raw_dataset)))\n",
        "print(raw_dataset[:5])\n",
        "#print(\"Shape of dataset is: %s\" % str(raw_dataset.shape))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Type of dataset is: <class 'pandas.core.frame.DataFrame'>\n",
            "  pdb_id  ... label\n",
            "0   2d3u  ...  6.92\n",
            "1   3cyx  ...  8.00\n",
            "2   3uo4  ...  6.52\n",
            "3   1p1q  ...  4.89\n",
            "4   3ag9  ...  8.05\n",
            "\n",
            "[5 rows x 7 columns]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GNilV3VXnB_j",
        "colab_type": "text"
      },
      "source": [
        "### Training the Model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WufupHBPnB_k",
        "colab_type": "text"
      },
      "source": [
        "Now that we've seen what our dataset looks like let's go ahead and do some python on this dataset."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "V7mYU5zfnB_m",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "import tensorflow as tf"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kDwy6gZinB_q",
        "colab_type": "text"
      },
      "source": [
        "TODO(rbharath): This tutorial still needs to be fleshed out."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wqS0gGXunB_s",
        "colab_type": "text"
      },
      "source": [
        "# Congratulations! Time to join the Community!\n",
        "\n",
        "Congratulations on completing this tutorial notebook! If you enjoyed working through the tutorial, and want to continue working with DeepChem, we encourage you to finish the rest of the tutorials in this series. You can also help the DeepChem community in the following ways:\n",
        "\n",
        "## Star DeepChem on [GitHub](https://github.com/deepchem/deepchem)\n",
        "This helps build awareness of the DeepChem project and the tools for open source drug discovery that we're trying to build.\n",
        "\n",
        "## Join the DeepChem Gitter\n",
        "The DeepChem [Gitter](https://gitter.im/deepchem/Lobby) hosts a number of scientists, developers, and enthusiasts interested in deep learning for the life sciences. Join the conversation!"
      ]
    }
  ]
}